package Controller

import (
	"github.com/gin-gonic/gin"
	"log"
	"math"
	"strconv"
	"time"
	"web_back_go/Common"
	"web_back_go/DAO/gorm"
	"web_back_go/DAO/gorm/GormModel"
	"web_back_go/Response"
)

func GetUserMessage(c *gin.Context) {
	currentStr := c.Query("current")
	sizeStr := c.Query("size")

	page, err := strconv.Atoi(currentStr)
	if err != nil || page < 1 {
		page = 1 // 默认第一页
	}

	size, err := strconv.Atoi(sizeStr)
	if err != nil || size < 1 {
		size = 10 // 默认每页10条
	}

	// 计算分页偏移量
	offset := (page - 1) * size
	userId, _ := Common.GetUserId(c)
	log.Println("userid是", userId)
	db := gorm.Db

	var total int64
	countQuery := db.Model(&GormModel.TzProdComm{}).
		Where(&GormModel.TzProdComm{UserID: userId}).
		Where("reply_content IS NOT NULL  AND reply_content != ''") //过滤没有回复的信息
	if err := countQuery.Count(&total).Error; err != nil {
		c.JSON(200, Response.ResponseBody{
			Code:    "A0001",
			Msg:     nil,
			Data:    nil,
			Version: "V1.0",
			Sign:    nil,
			Success: true,
			Fail:    false,
		})
		return
	}

	// 分页查询数据
	var prodComm []GormModel.TzProdComm
	dataQuery := db.
		Where(&GormModel.TzProdComm{UserID: userId}).
		Where("reply_content IS NOT NULL  AND reply_content != ''").
		Order("rec_time DESC") // 按时间倒序

	if err := dataQuery.Offset(offset).Limit(size).Find(&prodComm).Error; err != nil {

		c.JSON(200, Response.ResponseBody{
			Code:      "A0001",
			Data:      nil,
			Fail:      true,
			Msg:       "获取商品评论分页数据失败",
			Sign:      "",
			Success:   false,
			Timestamp: time.Now().Unix(),
			Version:   "V1.0",
		})
		return
	}

	// 构造响应数据
	c.JSON(200, Response.ResponseBody{
		Code: "00000",
		Data: Common.PageParam1[GormModel.TzPickAddr]{
			Current: currentStr,
			Total:   total,
			Size:    size,
			Records: prodComm,
			Pages:   int(math.Ceil(float64(total) / float64(size))),
		},
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		Sign:      "",
	})
}

func GetUserMessageCount(c *gin.Context) {
	userId, _ := Common.GetUserId(c)
	db := gorm.Db
	var total int64
	countQuery := db.Model(&GormModel.TzProdComm{}).
		Where(&GormModel.TzProdComm{UserID: userId}).
		Where("reply_content IS NOT NULL  AND reply_content != ''") //过滤没有回复的信息

	if err := countQuery.Count(&total).Error; err != nil {

		c.JSON(200, Response.ResponseBody{
			Code:    "A0001",
			Msg:     nil,
			Data:    nil,
			Version: "V1.0",
			Sign:    nil,
			Success: true,
			Fail:    false,
		})
		return
	}
	c.JSON(200, Response.ResponseBody{
		Code:      "00000",
		Data:      total,
		Msg:       nil,
		Success:   true,
		Fail:      false,
		Version:   "V1.0",
		Sign:      nil,
		Timestamp: time.Now().Unix(),
	})
}
